package com.cloudcc.mobile.view.wel;

import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cloudcc.cloudframe.CApplication;
import com.cloudcc.cloudframe.bus.EventList.LoginEvent;
import com.cloudcc.cloudframe.bus.EventList.ServerUrlEvent;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.LoginDBModel;
import com.cloudcc.mobile.entity.LoginSPModel;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.LoginPresenter;
import com.cloudcc.mobile.util.AESUtils;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.UIUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.login.LoginNewActivity;
import com.cloudcc.mobile.view.main.MainUIActivity;
import com.litesuits.android.log.Log;

import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.Locale;

import butterknife.Bind;

/**
 * 启动页
 *
 * @author Administrator
 * <hr>
 * 登录流程:<br>
 * 1、根据账号名称 去获取app的url 2、根据url去执行登录操作
 * <hr>
 */
public class WelcomeActivity extends BaseActivity {

    @Bind(R.id.progressBar1)
    ProgressBar progressBar;
    private boolean islogining = true;
    private LoginPresenter loginPresenter = new LoginPresenter();
    /**
     * 是否是第一次运行
     */
    private boolean isFirst;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    AppContext.isFenXiang = false;// 设为不能分享
                    Intent intent = new Intent(mContext, MainUIActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.in_from_right,
                            R.anim.out_to_left);// 动画
                    WelcomeActivity.this.finish();
                    break;
                case 0:
                    WelcomeActivity.this.finish();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 全屏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        dp2pxxScale();
    }

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        RunTimeManager.getInstance().setGoHome(false);
        Boolean isFirstIn = false;
        SharedPreferences pref = mContext.getSharedPreferences("myActivityName", 0);
        //取得相应的值，如果没有该值，说明还未写入，用true作为默认值
//		isFirstIn = pref.getBoolean("isFirstIn", true);
        SharedPreferences pref1 = mContext.getSharedPreferences("islogin", 0);
        boolean islogin = pref1.getBoolean("islogin", false);
        android.util.Log.i("TAG", "fist=========" + UserManager.getManager().isFrist());
        if (isFirstIn) {
            CApplication.isfirstyunxin = true;
            pref = mContext.getSharedPreferences("myActivityName", 0);
            SharedPreferences.Editor editor = pref.edit();
            editor.putBoolean("isFirstIn", false);
            editor.commit();
            enterGuide();
        } else {
            CApplication.isfirstyunxin = false;
//            if (UserManager.getManager().zhuxiao() || !islogin) {
//                Intent intent = new Intent(mContext,
//                        GuideViewActivity.class);
//                intent.putExtra("page.index", 5);
//                mContext.startActivity(intent);
//                finish();
//                UserManager.getManager().savezhuxiao(false);
//            } else {
            initData();

//            }

        }
    }


    private void initData() {
//		progressBar.setVisibility(View.VISIBLE);
//        LoginDBModel login = loginPresenter.getLastLogin();
        String login = PreferenceHelper.readString(this, "loginInfo", "login", "");
        LoginSPModel loginSPModel;
        if (login.length() > 0) {
            loginSPModel = JSON.parseObject(login, LoginSPModel.class);
        } else {
            loginSPModel = null;
        }
        if (null != loginSPModel) {
            if (StringUtils.isBlank(loginSPModel.userName)
                    || StringUtils.isBlank(loginSPModel.password)) {
                enterLogin();
                return;
            }
        }
        if (loginSPModel != null && loginSPModel.isAutoLogin && NetWork.detect(this)) {// 如果是默认选择了自动登录
            // 现在就去登录页面
            // 或者
            // 引导页面
            //  loginPresenter.getAppUrl(login.userName);


            String dePassword = AESUtils.getDePassword(loginSPModel.password);
            Log.d("mima", "mima:" + dePassword);
            if (TextUtils.isEmpty(dePassword)) {// 解密失败
                enterLogin();
                return;
            }
            loginPresenter.login(loginSPModel.userName, dePassword);
        } else {

            enterLogin();
        }
    }

    /**
     * 获取应用登录 url
     *
     * @param event
     */
    public void onEventMainThread(ServerUrlEvent event) {
        if (event.isError()) {
            enterLogin();
            return;
        }
        String url = event.getData().data.url;
        //String url = event.getData().result;
        UrlTools.url = url + "/";
        UrlManager.APP_UR = url;
        UrlTools.weixinUrl = url;
        LoginDBModel login = loginPresenter.getLastLogin();
        // 通过jni获取c代码里面保存的密码 然后解密出来
        String dePassword = AESUtils.getDePassword(login.password);
        Log.d("mima", "mima:" + dePassword);
        if (TextUtils.isEmpty(dePassword)) {// 解密失败
            enterLogin();
            return;
        }
        loginPresenter.login(login.userName, dePassword);
    }

    /**
     * 根据用户名密码 获取binding
     *
     * @param event
     */
    public void onEventMainThread(LoginEvent event) {
        LogUtils.d(TAG, "登录:" + event.isOk());
        if (event.isError()) {
            enterLogin();
            return;
        }
        RunTimeManager.setAppBinding(event.getData().binding);
        RunTimeManager.setAppLanguage(event.getData().userInfo.lang);
        RunTimeManager.setJuese(event.getData().userInfo.roleName);
        RunTimeManager.setJiandang(event.getData().userInfo.profileName);
        RunTimeManager.setLoginname((event.getData().userInfo.loginName));
        RunTimeManager.setId((event.getData().userInfo.orgId));
        RunTimeManager.setUserId((event.getData().userInfo.userId));
        RunTimeManager.setVersion(((event.getData().userInfo.version)));
        RunTimeManager.setTongshi(((event.getData().userInfo.showColleague)));
        RunTimeManager.setorgId((event.getData().userInfo.orgId));
        RunTimeManager.setUserName((event.getData().userInfo.userName));
        RunTimeManager.setIsUsingGotpFlag(event.getData().userInfo.isUsingGotpFlag);
        RunTimeManager.setIsBoundMfa(event.getData().userInfo.isBoundMfa);
        RunTimeManager.setProfileId(event.getData().userInfo.profileId);

        // 保存用户 注意密码
        UserModel user = event.getData().userInfo;
        UserManager.getManager().saveUser(user);
        if ("en".equals(event.getData().userInfo.lang)) {
            Resources resources = this.getResources();
            DisplayMetrics dm = resources.getDisplayMetrics();
            Configuration config = resources.getConfiguration();
            // 应用用户选择语言
            config.locale = Locale.ENGLISH;
            resources.updateConfiguration(config, dm);

        } else {
            Resources resources = this.getResources();
            DisplayMetrics dm = resources.getDisplayMetrics();
            Configuration config = resources.getConfiguration();
            // 应用用户选择语言
            config.locale = Locale.TRADITIONAL_CHINESE;
            resources.updateConfiguration(config, dm);
        }
//		if(isOPen(this)){
////			return;
//		}else{
//			openGPS(this);
//		}
//		openGPSSettings();
        // 进入到主页面
        enterAPP();

    }

    private void openGPSSettings() {
        LocationManager alm = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        if (alm
                .isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
        startActivityForResult(intent, 0); //此为设置完成后返回到获取界面
    }

    /**
     * 强制帮用户打开GPS
     *
     * @param context
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (CanceledException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static final boolean isOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）  
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）  
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    /**
     * 进入引导页面 2016-5-3
     */
    private void enterGuide() {
        Intent intent = new Intent(WelcomeActivity.this,
                GuideViewActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 进入登录页面 2016-5-3
     */
    private void enterLogin() {
        Intent intent = new Intent(WelcomeActivity.this, LoginNewActivity.class);
        startActivity(intent);
        this.finish();
    }

    /**
     * 进入app
     */
    private void enterAPP() {
        AppContext.isFenXiang = false;
        UIUtils.enterMainUI(mContext);
        finish();
    }

    @Override
    public int getLayoutId() {
        return R.layout.welcome;
    }

    @Override
    protected boolean hasEventLife() {
        return true;
    }

    //屏幕分辨率管理
    public void dp2pxxScale() {
        final float scale = this.getResources().getDisplayMetrics().density;
        RunTimeManager.getInstance().setSale(scale);
    }


}
